<template>
  <!-- 商品信息 -->
  <div class="component-giveaway-prod-table">
    <div
      class="default-btn"
      :class="{'disabled-btn': productItems.length === limit || pageType === 2 }"
      @click="selectProdHandle()"
    >
      {{ $t('giveaway.addInKindProd') }}
    </div>
    <div class="count-desc-text">
      {{ $t('giveaway.giveawayLimitTips') }}
    </div>
    <div
      v-if="!verifyFlag"
      class="error-tips"
    >
      {{ $t('giveaway.giveawayProdErrorTips') }}
    </div>
    <div
      v-if="productItems && productItems.length > 0"
      class="prodItem-table"
    >
      <el-table
        :data="productItems"
        header-cell-class-name="table-header"
        :span-method="tableSpanMethod"
        row-class-name="table-row"
        :style="tableWidth"
      >
        <el-table-column
          :label="$t('group.prodInfo')"
          prop="reason"
          fixed="left"
          align="center"
          width="320px"
        >
          <template #default="scope">
            <div class="prod-info-container">
              <div class="prod-image">
                <prod-pic
                  :pic="scope.row.pic"
                />
              </div>
              <div class="prod-name">
                <div class="prod-name-txt">
                  {{ scope.row.prodName }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('combo.participateSpec')"
          align="center"
          prop="skuName"
          width="200px"
        >
          <template #default="scope">
            {{ scope.row.skuName || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('product.price')"
          align="center"
          prop="price"
          width="200px"
        />
        <el-table-column
          prop="refundPrice"
          :label="$t('giveaway.refundPrice')"
          align="center"
          width="160px"
        >
          <template #header>
            {{ $t('giveaway.refundPrice') }}
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('giveaway.refundPriceTips')"
              placement="top"
            >
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">
            <div class="custom-rate">
              <input
                v-model.number="scope.row.refundPrice"
                :disabled="pageType === 2"
                type="number"
                :precision="2"
                :max="scope.row.price"
                :min="0"
                :step="0.01"
                class="tag-input-width"
                @keyup="
                  scope.row.refundPrice = String(scope.row.refundPrice).match(/\d+(\.\d{0,2})?/) ?
                    Number.parseFloat(String(scope.row.refundPrice).match(/\d+(\.\d{0,2})?/)[0]) :
                    ''
                "
                @blur="inputValue(scope.$index, scope.row.refundPrice, 'refundPrice', 0, scope.row.price)"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="giveawayNum"
          :label="$t('giveaway.giveawayNum')"
          align="center"
          width="160px"
        >
          <template #default="scope">
            <div class="custom-rate">
              <input
                v-model="scope.row.giveawayNum"
                :disabled="pageType === 2"
                type="number"
                :precision="0"
                :min="1"
                :max="99999999"
                :step="1"
                size="small"
                style="width: 80%;"
                class="tag-input-width"
                @keydown="restrictedInput"
                @keyup="
                  scope.row.giveawayNum = String(scope.row.giveawayNum).match(/[^0-9]/) ? 1 : scope.row.giveawayNum
                "
                @blur="inputValue(scope.$index, scope.row.giveawayNum, 'giveawayNum', 1, 99999999)"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="pageType === 1"
          align="center"
          :label="$t('crud.menu')"
          fixed="right"
          width="140px"
        >
          <template #default="scope">
            <div class="text-btn-con">
              <div
                class="default-btn text-btn"
                @click="deleteHandle(scope.$index)"
              >
                {{ $t('text.delBtn') }}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <sku-select
      v-if="addProdVisible"
      ref="ProdsSelectRef"
      :chosen-check-items="productItems"
      :limit="15"
      :limit-type="2"
      :item-data-type="2"
      :status="1"
      :is-active="0"
      :sku-status="1"
      :mold="1"
      @refresh-select-prods="selectProdItem"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs } from 'vue'
const emit = defineEmits(['refreshSelectProds'])
const props = defineProps({
  type: {
    default: 1,
    type: Number // 1 主商品 2 搭配商品
  },
  comboId: {
    default: 0,
    type: Number // 套餐id
  },
  limit: {
    default: -1,
    type: Number // 限制数量 -1代表没有限制
  },
  pageType: {
    default: 1,
    type: Number // 1：新增/编辑 2：查看
  }
})

const Data = reactive({
  addd: true,
  tableWidth: {
    width: '1180px'
  },
  productItems: [], // 已选择的商品项
  addProdVisible: false, // 添加商品弹窗是否可见
  verifyFlag: true, // 数据校验标记，true：正确，false：错误
  totalCount: 0, // 总出入库量
  failureCount: 0, // 失效的商品数量
  rowspan: {} // 表格合并数据
})

const { tableWidth, productItems, addProdVisible, verifyFlag } = toRefs(Data)

onMounted(() => {
  init()
})

const init = (productItems) => {
  Data.tableWidth.width = props.pageType === 1 ? '1180px' : '1040px'
  if (productItems) {
    computeRowspan(productItems)
    Data.productItems = productItems
  } else {
    Data.productItems = []
  }
}

const ProdsSelectRef = ref()
const selectProdHandle = () => {
  if (Data.productItems.length >= props.limit || props.pageType === 2) {
    return
  }
  Data.addProdVisible = true
  nextTick(() => {
    ProdsSelectRef.value.init()
  })
}

// 选择商品项回调
const selectProdItem = (prodItems) => {
  Data.productItems = []
  let requiredCount = 0
  prodItems.forEach(item => {
    item.refundPrice = item.refundPrice ? item.refundPrice : 0
    item.required = item.required === 0 ? 0 : 1
    requiredCount += item.required ? 1 : 0
    item.giveawayNum = item.giveawayNum ? item.giveawayNum : 1
  })
  computeRowspan(prodItems)
  emit('refreshSelectProds', prodItems)
  // 重置verifyFlag
  if (props.type === 1) {
    if (prodItems.length === 1) {
      Data.verifyFlag = true
    }
  } else {
    if (prodItems.length > 0 && prodItems.length < 5 && requiredCount > 0) {
      Data.verifyFlag = true
    }
  }
  Data.productItems = prodItems
}

const computeRowspan = (prodItems) => {
  Data.rowspan = {}
  let prodId = -1
  let firstIndex = -1
  for (let i = 0; i < prodItems.length; i++) {
    if (prodItems[i].prodId === prodId) {
      if (Data.rowspan[firstIndex]) {
        Data.rowspan[firstIndex] += 1
      } else {
        Data.rowspan[firstIndex] = 2
      }
    } else {
      firstIndex = i
      prodId = prodItems[i].prodId
      Data.rowspan[firstIndex] = 1
    }
  }
}

// eslint-disable-next-line no-unused-vars
const tableSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (Data.rowspan[rowIndex]) {
      return {
        rowspan: Data.rowspan[rowIndex],
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 校验数据，校验成功返回数据项，不成功返回null
const verifyDataForm = () => {
  if (Data.productItems.length > 0 && Data.productItems.length <= 15) {
    return Data.productItems
  } else {
    Data.verifyFlag = false
    return null
  }
}

// 限制输入框只能输入数字
const restrictedInput = (e) => {
  const key = e.key
  // 不允许输入'e'和'.'
  if (key === 'e' || key === '.') {
    e.returnValue = false
    return false
  }
  return true
}

// 输入值校验
const inputValue = (index, val, dataFields, min, max) => {
  const info = Data.productItems[index]
  if (index !== undefined && index !== null) {
    if (val > max) {
      info[dataFields] = max
      Data.productItems[index] = { ...info }
    }
    if (val < min || !val) {
      info[dataFields] = min
      Data.productItems[index] = { ...info }
    }
  }

  if (info[dataFields] === '' && dataFields === 'refundPrice') {
    info[dataFields] = 0
    Data.productItems[index] = { ...info }
  }
}

// 删除已选择的商品项
const deleteHandle = (index) => {
  Data.productItems.splice(index, 1)
  computeRowspan(Data.productItems)
}

defineExpose({
  verifyDataForm,
  init
})
</script>

<style lang="scss" scoped>
.component-giveaway-prod-table {
  width: 100%;
  .count-desc-text {
    margin-bottom: 4px;
    color: #888888;
    font-size: 14px;
  }
  .error-tips {
    color: #f56c6c;
    font-size: 12px;
    padding-bottom: 4px;
  }
  .disabled-btn {
    color: #C0C4CC;
    &:hover {
      cursor: not-allowed;
      color: #C0C4CC;
    }
  }
  .prodItem-table {
    .prod-info-container {
      height: 100%;
      display: flex;
      justify-content: space-between;
      .prod-image {
        margin-right: 20px;
        width: 80px;
        height: 80px;
        flex-shrink: 0;
      }
      .prod-name {
        flex: 1;
        height: 80px;
        display: flex;
        flex-direction: column;
        text-align: start;
        justify-content: center;
        .prod-name-txt {
          font-size: 14px;
          color: #333333;
          word-break: break-all;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          line-break: anywhere;
        }
      }
    }
    // 表格输入框
    .tag-input-width {
      width: 100%;
      padding-left: 5px;
      padding-right: 0;
      border: 1px solid #DCDCDC;
      border-radius: 2px;
      height: 32px;
      line-height: 32px;
      box-sizing: border-box;
      &:focus {
        outline: 0;
      }
    }
  }
}
</style>
